import { NumberFormat, getEcharsData96 } from '../../utils';
import { headerMap } from './helper';
import { TIME_96, TIME_24 } from '@/pages/ETrade/components/helper';

// 计算算术均价
export const _getTotalStatementEnergyPrice = (data, name) => {
  const echartsValues = [];
  const newData = []; // 过滤有综合电价的数据
  let totalStatementEnergyIncome = 0;
  data.map((item) => {
    if (item.data && item.data[name]) {
      newData.push(item);
    }
  });
  newData.map((item) => {
    totalStatementEnergyIncome += Number(item.data[name]);
  });

  data.map((v) => {
    const result = totalStatementEnergyIncome / newData.length;
    echartsValues.push(
      v?.data?.provincialRealtimeClearingQuantity &&
        v?.data?.provincialRealtimeClearingQuantity !== '0.00'
        ? NumberFormat(result, 100)
        : '-',
    );
  });
  return echartsValues;
};

// 计算价格均线
export const _getPriceAverage = (data) => {
  const echartsValues = [];

  data.map((v) => {
    const result =
      (v?.data?.superpositionLongTermQuantity * v?.data?.longTermEstimatedAveragePrice +
        parseFloat(v?.data?.totalSpotCheckAllocationIncome)) /
      v?.data?.reckoningQuantity;
    echartsValues.push(
      v?.data?.reckoningQuantity && v?.data?.reckoningQuantity !== '0.00'
        ? NumberFormat(result, 100)
        : '-',
    );
  });
  return echartsValues;
};

//甘肃 计算综合电价
export const getTotalStatementPrice_gansu = (data) => {
  const echartsValues = [];
  const totalStatementEnergyIncome = getEcharsData96(data, 'totalStatementEnergyIncome'); // 综合电费之和
  const totalStatementQuantity = getEcharsData96(data, 'totalStatementEnergyQuantity'); // 综合电量之和
  totalStatementEnergyIncome.map((item, index) => {
    let result = 0;
    if (totalStatementQuantity[index] !== 0) {
      result = item / totalStatementQuantity[index];
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};

// 计算综合电价的平均电价
export const getTotalStatementEnergyPrice = (data) => {
  const echartsValues = [];
  let totalStatementEnergyIncome = 0;
  data.map((item) => {
    totalStatementEnergyIncome += Number(item);
  });

  data.map(() => {
    const result = totalStatementEnergyIncome / data.length;
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};

// 计算两数之和相除
export const getPowerForecastPrice = (data, denominatorName, molecularName) => {
  const echartsValues = [];
  const denominatorNameAdd = getEcharsData96(data, denominatorName); // 分母参数之和
  const molecularNameAdd = getEcharsData96(data, molecularName); // 分子参数之和
  denominatorNameAdd.map((item, index) => {
    let result = 0;
    if (molecularNameAdd[index] !== 0) {
      result = item / molecularNameAdd[index];
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};

// 计算96点正负电费
export const getEcharsData96_Icome = (data, quantityName, priceName, toFixedThree) => {
  const echartsValues = [];
  const tofix = toFixedThree ? 1000 : 100; // 保留几位小数 1000-3位  100-两位
  data.map((item) => {
    (item?.children || []).map((y, index) => {
      if (echartsValues[index] || echartsValues[index] === 0) {
        const result =
          Number(echartsValues[index]) +
          NumberFormat(Number(y.data[quantityName]) * Number(y.data[priceName]), tofix);
        echartsValues[index] = NumberFormat(result, tofix);
      } else {
        echartsValues.push(
          y.data === null || y.data[quantityName] === null || y.data[priceName] === null
            ? null
            : NumberFormat(Number(y.data[quantityName]) * Number(y.data[priceName]), tofix),
        );
      }
    });
  });
  return echartsValues;
};

// 计算正负电价
export const getCorrectNegativePrice = (data, quantityName, priceName) => {
  const echartsValues = [];
  const income = getEcharsData96_Icome(data, quantityName, priceName); // 电费
  const quantity = getEcharsData96(data, quantityName); // 电量

  income.map((item, index) => {
    let result;
    if (!!quantity[index]) {
      result = NumberFormat(item / quantity[index], 100);
    }
    echartsValues.push(result);
  });
  return echartsValues;
};

//子页面处理数据方法选择
export const dealDataChoose = (funcName, ...key) => {
  const map = {
    forMater,
    getEcharsData96,
    getTotalStatementPrice_gansu,
    getTotalStatementEnergyPrice,
    _getTotalStatementEnergyPrice,
    getPowerForecastPrice,
    getCorrectNegativePrice,
  };
  return map[funcName](...key);
};

export const dealDataMap = (chartMap, chartData, dataMap) => {
  Object.values(chartMap).map((item) => {
    Object.entries(item).map((t) => {
      const _data = t[1].useData === false ? [] : [chartData];
      const _funcName = t[1].funcName;
      const _param = t[1]?.param || [];
      const dependentValue = dataMap?.[t[1]?.dependentValue];

      dataMap[t[0]] = dealDataChoose(_funcName, ..._data, ..._param, dependentValue);
    });
  });
};

const dealFunc = (tag, meta, title, value, crumbsName, id, index, pointNum) => {
  let obj = {};
  const _title =
    tag === '时点'
      ? pointNum === '96'
        ? TIME_96[title - 1]
        : TIME_24[title - 1]
      : tag === '日期'
      ? title.replaceAll('-', '')
      : title;
  obj = {
    title: _title,
    tag,
    name: _title,
    crumbsName: crumbsName ? crumbsName + '__' + _title : _title,
    id: id ? id + '-' + index : index + 1,
  };
  meta.forEach((_t, _i) => {
    if (_i > 1) {
      obj[headerMap[_t]] = _t.includes('电量')
        ? parseFloat(value[_i] ? value[_i] : '0').toFixed(3)
        : parseFloat(value[_i] ? value[_i] : '0').toFixed(2);
    } else {
      obj[headerMap[_t]] = value[_i];
    }
  });

  return obj;
};

const totalDealFunc = (tag, meta, title, value) => {
  let obj = {};
  obj = {
    title,
    tag,
    name: title,
    crumbsName: title,
  };
  meta.forEach((_t, _i) => {
    if (_i > 1) {
      obj[headerMap[_t]] = _t.includes('电量')
        ? parseFloat(value[_i]).toFixed(3)
        : parseFloat(value[_i]).toFixed(2);
    } else {
      obj[headerMap[_t]] = value[_i];
    }
  });
  obj.children = [];
  return obj;
};

export const getNewDataSource = (dataSource, order, pointNum) => {
  if (!dataSource?.size) return [];
  const formatForTable = (item, optionName, crumbsName = '', id = '', index = 0) => {
    const arr = [];
    Object.entries(item).map((t, i) => {
      if (t[0] === 'total') {
        return;
      }
      //最后一个维度为数组
      if (t[1] instanceof Array) {
        arr.push(
          dealFunc(optionName[index], dataSource.meta, t[0], t[1], crumbsName, id, i, pointNum),
        );
        return;
      }
      const obj = dealFunc(
        optionName[index],
        dataSource.meta,
        t[0],
        t[1].total,
        crumbsName,
        id,
        i,
        pointNum,
      );
      obj.children = formatForTable(t[1], optionName, obj.crumbsName, obj.id, index + 1);
      arr.push(obj);
    });
    arr.sort((a, b) => {
      if (optionName[index] === '交易单元') {
        return a.title.localeCompare(b.title, 'zh-CN');
      }
      //默认时点排序方式
      return a.title > b.title ? 1 : -1;
    });
    return arr;
  };
  // 添加合计行
  const result = [
    totalDealFunc(order[0], dataSource.meta, '合计', dataSource.data.total),
    ...formatForTable(dataSource.data, order),
  ];
  return result;
};

// 格式化导出数据
export const formatJson = (filterVal, jsonData) => {
  return jsonData.map((v) => {
    return filterVal.map((j) => {
      return v[j] ?? '-';
    });
  });
};

// 根据名称拿指定数据
export const forMater = (data, name) => {
  const newValue = [];
  data.map((item) => {
    newValue.push(item[name] === null ? '' : item[name]);
  });
  return newValue;
};
